﻿using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using ClickOnce.Install.Settings;
using Core;
using Core.Net;
using log4net;
using log4net.Config;
using StructureMap;
using Topshelf;

namespace ClickOnce.Install.Service
{
    class Program
    {
        private static readonly string UserAgent = "ClickOnce.Install.Service " + Assembly.GetCallingAssembly().GetName().Version;

        static void Main(string[] args)
        {
            Configure();
            HostFactory.Run(x =>
            {
                x.Service<ApplicationService>(s =>
                    {
                        s.ConstructUsing(ObjectFactory.GetInstance<ApplicationService>);
                        s.WhenStarted(_ => _.Start());
                        s.WhenStopped(_ => _.Stop());
                    });

                x.StartAutomatically();
                x.RunAsLocalSystem();
                x.EnableServiceRecovery(config =>
                {
                    config.RestartService(1);
                    config.RestartService(1);
                    config.RestartService(1);
                });

                x.SetDescription("ClickOnce runtime DFSVC.EXE.");
                x.SetDisplayName("ClickOnce runtime");
                x.SetServiceName("DFSVC.EXE");
            });

        }

        static void Configure()
        {
            Task.Factory.StartNew(ConfigureProperties);

            FileInfo log4NetConfig = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config"));
            if (log4NetConfig.Exists)
                XmlConfigurator.Configure(log4NetConfig);
            ObjectFactory.Configure(config =>
            {
                config.AddRegistry<ClickOnceInstallRegistry>();
                config.AddRegistry<ClickOnceInstallSettingsRegistry>();
            });
        }

        static void ConfigureProperties()
        {
            GlobalContext.Properties[PropertyName.MachineID] = NetworkInfo.PhysicalMacAddress;
            GlobalContext.Properties[PropertyName.MachineName] = Environment.MachineName;
            GlobalContext.Properties[PropertyName.UserAgent] = UserAgent;   
        }
    }
}
